/*
 * ========================================================
 * Copyright(c) 2014 杭州龙骞科技-版权所有
 * ========================================================
 * 本软件由杭州龙骞科技所有, 未经书面许可, 任何单位和个人不得以
 * 任何形式复制代码的部分或全部, 并以任何形式传播。
 * 公司网址
 * http://www.hzdracom.com/
 * ========================================================
 */
package com.shwread.android.ui.page;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.NewActionHelp;
import com.ciko.code.bean.UserBean;
import com.shwread.android.qysw.activity.MainActivity;
import com.shwread.android.qysw10000204.R;
import com.shwread.android.ui.dialog.DatePickerDialog;
import com.shwread.android.ui.dialog.DatePickerListener;
import com.shwread.android.ui.dialog.HeaderImgDialog;
import com.shwread.android.ui.dialog.HeaderImgDialog.OnUserinfoMenuClickListener;
import com.shwread.android.ui.dialog.SexDialog;
import com.shwread.android.ui.dialog.SexListener;
import com.shwread.android.ui.widget.CircleImageView;
import com.shwread.http.base.TextHttpResponseHandler;
import com.shwread.http.util.JSONUtil;
import com.shwread.httpsdk.http.callback.ActionListener;
import com.shwread.httpsdk.http.callback.BaseAction;
import com.tgx.tina.android.ipc.framework.IUIPage;

import org.apache.http.Header;
import org.json.JSONException;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.UUID;

import base.tina.core.task.infc.ITaskResult;
import logic.constants.Const;
import logic.constants.DefaultConsts;
import logic.util.MultiCard;
import logic.util.PicassoUtil;
import logic.util.SDcardUtil;
import logic.util.Util;
import logic.util.Utils;


/**
 * @Project： Lqyd_Android
 * @Title：PersonalInfoPage
 * @Description：个人信息页面
 * @Author：wayne
 * @Date：2014年8月14日上午11:13:43
 */
public class PersonalInfoPage
        extends
        AbstractUIPage<MainActivity>
        implements
        OnClickListener,
        OnUserinfoMenuClickListener,
        SexListener {
    private final String imageName = "UserHeader.jpg";
    private TextView tvTitle;
    private Button btnBack;
    private CircleImageView imgHeader;
    private RelativeLayout rlNickName;
    private RelativeLayout rlSex;
    private RelativeLayout rlAge;
    private TextView tvAccount;
    private TextView tvNickName;
    private TextView tvSex;
    private TextView tvAge;

    private UserBean user;
    private String nickName = "";

    private HeaderImgDialog imgSetDialog;
    private SexDialog sexDialog;

    private String sexValue;
    private String sexMorF;

    public void setUser(UserBean user) {
        this.user = user;
    }

    public void setSex(String int1) {
        if (Util.isEmpty(int1)) return;
        if (int1.equals("0")) {
            tvSex.setText("男");
        } else if (int1.equals("1")) {
            tvSex.setText("女");
        }

    }

    //	private static PersonalInfoPage instance;
    //
    //	public static PersonalInfoPage getInstance(PersonalInfoActivity t) {
    //		if (null == instance) instance = new PersonalInfoPage(t);
    //		return instance;
    //	}

    public PersonalInfoPage(MainActivity t) {
        super(t);
    }

    @Override
    public <E extends Activity> View createView(E arg0, int arg1) {
        if (null != curMyView) return curMyView;

        curMyView = bActivity.getLayoutInflater().inflate(R.layout.user_info, null);

        initView();
        setLinstener();

        return curMyView;
    }

    void initView() {
        tvTitle = (TextView) curMyView.findViewById(R.id.common_header_name);
        tvTitle.setText("个人信息");
        btnBack = (Button) curMyView.findViewById(R.id.common_header_back);
        btnBack.setVisibility(View.VISIBLE);
        imgHeader = (CircleImageView) curMyView.findViewById(R.id.user_info_head_img);
        tvAccount = (TextView) curMyView.findViewById(R.id.user_info_account_tv);
        rlNickName = (RelativeLayout) curMyView.findViewById(R.id.user_info_name_ll);
        rlSex = (RelativeLayout) curMyView.findViewById(R.id.user_info_sex_ll);
        rlAge = (RelativeLayout) curMyView.findViewById(R.id.user_info_age_ll);
        tvNickName = (TextView) curMyView.findViewById(R.id.user_info_name_tv);
        tvSex = (TextView) curMyView.findViewById(R.id.user_info_sex_tv);
        tvAge = (TextView) curMyView.findViewById(R.id.user_info_age_tv);

        imgSetDialog = new HeaderImgDialog(bActivity, this);

        vHometown = curMyView.findViewById(R.id.user_info_hometown_ll);
        vLivenow = curMyView.findViewById(R.id.user_info_livenow_ll);
        vJob = curMyView.findViewById(R.id.user_info_job_ll);
        vInterest = curMyView.findViewById(R.id.user_info_interest_ll);
        vDesc = curMyView.findViewById(R.id.user_info_desc_ll);
        tvHometown = (TextView) curMyView.findViewById(R.id.user_info_hometown_tv);
        tvLivenow = (TextView) curMyView.findViewById(R.id.user_info_livenow_tv);
        tvJob = (TextView) curMyView.findViewById(R.id.user_info_job_tv);
        tvInterest = (TextView) curMyView.findViewById(R.id.user_info_interest_tv);
        tvDesc = (TextView) curMyView.findViewById(R.id.user_info_desc_tv);

    }

    private View vHometown;//user_info_hometown_ll
    private View vLivenow;//user_info_livenow_ll
    private View vJob;//user_info_job_ll
    private View vInterest;//user_info_interest_ll
    private View vDesc;//user_info_desc_ll
    private TextView tvHometown;
    private TextView tvLivenow;
    private TextView tvJob;
    private TextView tvInterest;
    private TextView tvDesc;

    void setLinstener() {
        vHometown.setOnClickListener(this);
        vLivenow.setOnClickListener(this);
        vJob.setOnClickListener(this);
        vInterest.setOnClickListener(this);
        vDesc.setOnClickListener(this);

        btnBack.setOnClickListener(this);
        imgHeader.setOnClickListener(this);
        rlNickName.setOnClickListener(this);
        rlSex.setOnClickListener(this);
        rlAge.setOnClickListener(this);
        tvNickName.setOnClickListener(this);
        if (user != null && Util.isNotEmpty(user.getHeadImage())) {
            PicassoUtil.load(context, user.getHeadImage(), R.drawable.user_head_img, imgHeader);
        }
    }

    void initData() {
        if (null == user) return;
        if (Util.isEmpty(nickName)) {
            tvNickName.setText(user.getNickName());
        } else {
            tvNickName.setText(nickName);
            user.setNickName(nickName);
        }
        tvAccount.setText(Util.isEmpty(user.getAccount()) ? "" : user.getAccount());
        sexValue = user.getSex();
        setSex(sexValue);
        tvAge.setText(Util.isEmpty(user.getBirthday()) || user.getBirthday().equals("请选择") ? "" : user.getBirthday());
        tvHometown.setText(TextUtils.isEmpty(user.getHomeTown()) ? "" : user.getHomeTown());
        tvLivenow.setText(TextUtils.isEmpty(user.getLiveNow()) ? "" : user.getLiveNow());
        tvJob.setText(TextUtils.isEmpty(user.getJob()) ? "" : user.getJob());
        tvInterest.setText(TextUtils.isEmpty(user.getInterest()) ? "" : user.getInterest());
        tvDesc.setText(TextUtils.isEmpty(user.getDesc()) ? "" : user.getDesc());
    }

    @Override
    public int enter(IUIPage<?> arg0) {
        initData();

        return 0;
    }

    @Override
    public int leave(IUIPage<?> arg0) {
        return 0;
    }

    @Override
    public void notifyView(int arg0, Bundle bundle) {
        switch (arg0) {
            case DefaultConsts.PERSONAL_UPDATEUI_FACE_UPDATE_HEAD:
                Bitmap photo = bundle.getParcelable("data");
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                photo.compress(Bitmap.CompressFormat.JPEG, 100, stream);
                if (photo != null) {
                    byte[] photoData = Util.getImageDataByLimitSize(photo, 100, 5000); // 图片不能大于3k
                    // 释放图片
                    photo.recycle();
                    photo = null;
                    if (photoData != null) {
                        try {
                            final String path = SDcardUtil.getTempPath().getPath();
                            Util.byte2File(photoData, path, imageName);
                            //    	                    new UploadUserImageAction1(bActivity, path+"/"+imageName, new UploadImageAction()).start();
                            NewActionHelp.uploadUserImage(bActivity, path + "/" + imageName, new UploadImageHandler());
                        } catch (Exception e) {
                            System.out.println("上传头像，创建本地图片失败");
                            e.printStackTrace();
                        } finally {
                            photoData = null;
                        }
                    } else {
                        Util.showToast(bActivity, "头像图片大小超过限制");
                    }
                }
                break;
            case DefaultConsts.PERSONAL_UPDATEUI_USERINFO_SEX:
                //				new ModAccountInfoAction(bActivity, "",sexValue, "", "", "", "", new SexListener()).start();
                NewActionHelp.modAccountInfo(bActivity, "", sexValue, "", "", "", "", new SexHandler());
                break;
            case DefaultConsts.PERSONAL_UPDATEUI_USERINFO_BIRTHDAY:
                if (user != null) {
                    //					new ModAccountInfoAction(bActivity, "", "" , user.getBirthday(), "", "", "", new SexListener()).start();
                    NewActionHelp.modAccountInfo(bActivity, "", "", user.getBirthday(), "", "", "", new SexHandler());
                }
                break;
            default:
                break;
        }
    }

    private class UploadImageHandler
            extends
            TextHttpResponseHandler {

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {

        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, String responseString) {
            try {
                if (Util.isEmpty(JSONUtil.getString(responseString))) return;
                PicassoUtil.load(context, JSONUtil.getString(responseString), R.drawable.user_head_img, imgHeader);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

    }

    private class UploadImageAction
            extends
            BaseAction {
        @Override
        public void OK(final Object obj) {
            if (Util.isEmpty(obj.toString())) return;
            bActivity.getUIHandler().post(new Runnable() {
                @Override
                public void run() {
                    PicassoUtil.load(context, obj.toString(), R.drawable.user_head_img, imgHeader);
                }
            });
        }
    }

    @Override
    public void setStatus(int arg0) {

    }

    @Override
    public View updateView(int arg0, ITaskResult arg1) {
        return null;
    }

    private void changeInfo(String lable, String defaultValue) {
        PersonalChangeUserInfoPage page = new PersonalChangeUserInfoPage(bActivity, user);
        page.setLable(lable, defaultValue);
        bActivity.changePage(page, DEFAULT_STATUS);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.user_info_hometown_ll:
                changeInfo(PersonalChangeUserInfoPage.TYPE_HOMETOWN, user.getHomeTown());
                break;
            case R.id.user_info_livenow_ll:
                changeInfo(PersonalChangeUserInfoPage.TYPE_LIVENOW, user.getLiveNow());
                break;
            case R.id.user_info_job_ll:
                changeInfo(PersonalChangeUserInfoPage.TYPE_JOB, user.getJob());
                break;
            case R.id.user_info_interest_ll:
                changeInfo(PersonalChangeUserInfoPage.TYPE_INTEREST, user.getInterest());
                break;
            case R.id.user_info_desc_ll:
                changeInfo(PersonalChangeUserInfoPage.TYPE_DESC, user.getDesc());
                break;
            case R.id.common_header_back:
                bActivity.onBackPressed();
                break;
            case R.id.user_info_head_img:
                if (user == null) {
                    break;
                }
                //				bActivity.startActivity(new Intent(bActivity,AtlasActivity.class));
                imgSetDialog.show();
                break;
            case R.id.user_info_name_ll:
            case R.id.user_info_name_tv:
                if (user == null) {
                    break;
                }
                PersonalChangeNamePage page = new PersonalChangeNamePage(bActivity, user);
                bActivity.changePage(page, DEFAULT_STATUS);
                //				Intent intent2 = new Intent();
                //				intent2.setClass(bActivity, ImageTextActivity.class);
                //				intent2.putExtra(DefaultConsts.title_s, "中国金雕5完成一阶段飞行 创最大续航时间等4纪录");
                //				intent2.putExtra(DefaultConsts.req_url_s, "http://news.ifeng.com/a/20150121/42981840_0.shtml");
                //				bActivity.startActivity(intent2);
                break;
            case R.id.user_info_sex_ll:
                int value = -1;
                if (user == null) {
                    break;
                }
                value = Integer.parseInt(Utils.isEmpty(user.getSex()) ? "-1" : user.getSex());
                sexDialog = new SexDialog(bActivity, value, this);
                sexDialog.show();
                break;
            case R.id.user_info_age_ll:
                if (user == null) {
                    break;
                }
                new DatePickerDialog(bActivity, tvAge.getText().toString().trim(), new MyDatePickerListener()).show();
                break;
            default:
                break;
        }

    }

    private class MyDatePickerListener
            implements
            DatePickerListener {
        @Override
        public void onSelect(String value) {
            if (user != null) user.setBirthday(value);
            tvAge.setText(value);
        }
    }

    public static File mImageFile; //图片文件

    @Override
    public void openCamera() {
        if (Util.isSDCardSapceForWriteWithTip(bActivity, MultiCard.TYPE_IMAGE, 0, true)) {
            return;
        }
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        String fileName = UUID.randomUUID().toString() + ".jpg";
        mImageFile = new File(Util.getWritePathIgnoreError(fileName));
        Uri capturedImgUri = Uri.fromFile(mImageFile);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, capturedImgUri);
        try {
            Intent wrapperIntent = Intent.createChooser(intent, null);
            bActivity.startActivityForResult(wrapperIntent, Const.CAPTURE_IMAGE);
        } catch (ActivityNotFoundException e) {
            Util.showToast(bActivity, "您的手机没有摄像头");
        }

    }

    @Override
    public void openLocal() {
        if (Util.isSDCardSapceForWriteWithTip(bActivity, MultiCard.TYPE_IMAGE, 0, true)) {
            return;
        }
        Intent mIntent = new Intent(Intent.ACTION_GET_CONTENT);
        mIntent.setType("image/*");
        Intent wrapperIntent = Intent.createChooser(mIntent, null);
        bActivity.startActivityForResult(wrapperIntent, Const.GET_LOCAL_IMAGE);

    }

    class SexHandler
            extends
            TextHttpResponseHandler {

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            if (statusCode > 1000) {
                try {
                    Util.showToast(bActivity, JSONUtil.getString(responseString));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, String responseString) {
            Util.showToast(bActivity, "修改成功");
            tvSex.setText(sexMorF);

        }

    }

    class SexListener
            implements
            ActionListener {
        @Override
        public void OK(Object obj) {
            bActivity.getUIHandler().post(new Runnable() {
                @Override
                public void run() {
                    Util.showToast(bActivity, "修改成功");
                    tvSex.setText(sexMorF);
                }
            });
        }

        @Override
        public void ERROR(int resultCode, final String message) {
            bActivity.getUIHandler().post(new Runnable() {

                @Override
                public void run() {
                    Util.showToast(bActivity, message);
                }
            });
        }

        @Override
        public void HTTPERROR(int statusCode) {

        }

    }

    @Override
    public void onSelect(int sex) {
        if (sex == 0) {
            sexValue = "0";
            sexMorF = "男";
            user.setSex(sexValue);
        } else if (sex == 1) {
            sexValue = "1";
            sexMorF = "女";
            user.setSex(sexValue);
        }
    }

}
